package com.ct.controller.upload;

import com.alibaba.fastjson.JSONObject;
import com.ct.commons.BaseController;
import com.ct.commons.annotation.HasAdmin;
import com.ct.commons.annotation.PermissionApi;
import com.ct.commons.aspect.limiter.AccessIpLimiter;
import com.ct.controller.upload.service.FileService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 公共模块-文件上传
 */
@RestController
//@PermissionApi(title = "OSS模块",path="/api/v1/oss",code = "I1000",sorted = 10)
public class OssController extends BaseController {

    @Autowired
    private FileService fileService;

    /**
     * 阿里云OSS文件上传
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("/oss/upload/file")
    @HasAdmin
    @AccessIpLimiter
    //@PermissionApi(title = "阿里云OSS文件上传",path="/api/v1/oss/upload/file",code = "I1001",sorted = 1)
    public JSONObject fileUploadComment(@RequestParam(value = "file", required = true) MultipartFile file, HttpServletRequest request) throws IOException {
        String path = request.getParameter("path");
        String oldName = request.getParameter("oldName");
        //给editormd进行回调
        JSONObject res = new JSONObject();
        // 上传图片文件到oss
        String url = fileService.upload(file, path,oldName);
        res.put("url",url);
        res.put("filename",file.getName());
        res.put("filesize",file.getSize());
        res.put("filetype",file.getContentType());
        res.put("success", "1");
        res.put("message", "upload success!");
        return res;
    }


    /**
     * 阿里云OSS文件上传--用于编辑器
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("/oss/upload/mdeditor")
    @HasAdmin
    @AccessIpLimiter
    //@PermissionApi(title = "阿里云OSS文件上传-用于编辑器",path="/api/v1/oss/upload/mdeditor",code = "I1002",sorted = 2)
    public JSONObject fileUploadUserhome(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request) throws IOException {
        // 上传图片文件到oss
        String path = request.getParameter("path");
        String oldName = request.getParameter("oldName");
        //给editormd进行回调
        JSONObject res = new JSONObject();
        // 上传图片文件到oss
        String url = fileService.upload(file, path,oldName);
        //给editormd进行回调
        res.put("url",url);
        res.put("success", 1);
        res.put("message", "upload success!");

        return res;
    }
}
